package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.RefreshRoomDeviceEvent;
import com.qiantu.phone.ui.activity.AddRoomActivity;
import com.qiantu.phone.ui.activity.FloorSettingActivity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.activity.RoomLinkageActivity;
import com.qiantu.phone.ui.activity.RoomSettingActivity;
import com.qiantu.phone.ui.adapter.FloorListBigAdapter;
import com.qiantu.phone.ui.adapter.FloorListSmallAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class FloorListFragment extends AppFragment<AppActivity> {
    private static final int EDIT_ROOM_CODE = 777;
    private int showType = 1;
    private RecyclerView floorRecyclerView;
    private RecyclerView floorSmallRecyclerView;

    //0全部、1时间变化、2环境变化、4设备变化
    private FloorListBigAdapter mFloorListBigAdapter;
    //0全部、1时间变化、2环境变化、4设备变化
    private FloorListSmallAdapter mFloorListSmallAdapter;
    public List<FloorBean> floors;

    public static FloorListFragment newInstance(int type) {
        FloorListFragment fragment = new FloorListFragment();
        Bundle bundle = new Bundle();
        fragment.setShowType(type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public int getShowType() {
        return showType;
    }

    public void setShowType(int showType) {
        this.showType = showType;
    }

    protected int getLayoutId() {
        return R.layout.fragment_room_list;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        floorRecyclerView = findViewById(R.id.room_recycler_view);
        floorSmallRecyclerView = findViewById(R.id.room_small_recycler_view);
    }

    private void initRecyclerView() {
        floorRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mFloorListBigAdapter = new FloorListBigAdapter(getContext());
        floorRecyclerView.setAdapter(mFloorListBigAdapter);
        mFloorListBigAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                FloorBean floorBean = mFloorListBigAdapter.getData().get(position);
                Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                if(floorBean.getType() == 1){
                    intent.putExtra("type", 2);
                }else{
                    intent.putExtra("type", 1);
                }
                intent.putExtra("roomSerialNo", floorBean.getFloorSerialNo());
                intent.putExtra("title", floorBean.getFloorName());
                startActivity(intent);
            }
        });
        mFloorListBigAdapter.setOnChildClickListener(R.id.btn_setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                FloorBean floorBean  = mFloorListBigAdapter.getData().get(position);
                Intent intent = new Intent(getActivity(), FloorSettingActivity.class);
                if(floorBean.getType() == 1){
                    intent.putExtra("type", 2);
                }else{
                    intent.putExtra("type", 1);
                }
                intent.putExtra("floorSerialNo", floorBean.getFloorSerialNo());
                startActivity(intent);
            }
        });
        mFloorListBigAdapter.setOnChildClickListener(R.id.btn_close, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                FloorBean floorBean = mFloorListBigAdapter.getData().get(position);
                closeAllDevice(floorBean);
            }
        });

        mFloorListBigAdapter.setOnChildClickListener(R.id.btn_roomLinkage, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                FloorBean floorBean  = mFloorListBigAdapter.getData().get(position);
                if(floorBean.getType() == 1){//全屋
                    RoomLinkageActivity.start(getContext(),"",0);
                }else{
                    RoomLinkageActivity.start(getContext(),floorBean.getFloorSerialNo(),1);
                }
            }
        });

        mFloorListBigAdapter.setData(floors);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        floorSmallRecyclerView.setLayoutManager(gridLayoutManager);
        mFloorListSmallAdapter = new FloorListSmallAdapter(getContext());
        floorSmallRecyclerView.setAdapter(mFloorListSmallAdapter);
        mFloorListSmallAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                FloorBean floorBean = mFloorListSmallAdapter.getData().get(position);
                Intent intent = new Intent(getActivity(), RoomDeviceActivity.class);
                if(floorBean.getType() == 1){
                    intent.putExtra("type", 2);
                }else{
                    intent.putExtra("type", 1);
                }
                intent.putExtra("roomSerialNo", floorBean.getFloorSerialNo());
                intent.putExtra("title", floorBean.getFloorName());
                startActivity(intent);
            }
        });
        mFloorListSmallAdapter.setOnChildClickListener(R.id.btn_all_close, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                FloorBean floorBean = mFloorListSmallAdapter.getData().get(position);
                closeAllDevice(floorBean);
            }
        });
        mFloorListSmallAdapter.setData(floors);
        setViewShow();
    }

    public void changeShowType(int showType){
        this.showType = showType;
        setViewShow();
    }

    public void setViewShow() {
        if(floorRecyclerView == null){
            return;
        }
        if (showType == 0) {
            floorRecyclerView.setVisibility(View.VISIBLE);
            floorSmallRecyclerView.setVisibility(View.GONE);
        } else {
            floorRecyclerView.setVisibility(View.GONE);
            floorSmallRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    public void closeAllDevice(FloorBean floorBean){
        List<DeviceBean> devices;
        if(floorBean.getType() == 1){
            devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevices();
        }else{
            devices = LLDeviceDBManager.getInstance(getContext()).getHomeAvailableDeviceByFloor(floorBean.getFloorSerialNo());
        }

        List<Map<String, Object>> list = new ArrayList();
        List<Map<String, Object>> groups = new ArrayList();
        List<DeviceBean> newDeviceBean = new ArrayList();

        for(DeviceBean deviceBean : devices){
            if(deviceBean.getType().equals("light") && !deviceBean.getIsDisable()){
                Map<String, Object> option = new HashMap<>();
                option.put(LLDeviceUtil.POWER, 0);
                Map<String, Object> status = new HashMap<>();
                status.put(LLDeviceUtil.STATUS, option);
                Map<String, Object> deviceItem = new HashMap<>();
                deviceItem.put("stateData", status);
                if(deviceBean.getDeviceGroup() == 0){
                    deviceItem.put("deviceSerialNo", deviceBean.getDeviceSerialNo());
                    list.add(deviceItem);
                    deviceBean.setPower(0);
                    newDeviceBean.add(deviceBean);
                }else{
                    deviceItem.put("deviceGroupSerialNo", deviceBean.getDeviceSerialNo());
                    groups.add(deviceItem);
                }
            }
        }
        LLHttpManager.deviceAllClose(getActivity(), list, new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                LLDeviceDBManager.getInstance(getContext()).putInTx(newDeviceBean);
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void No_equipment() {
        floorRecyclerView.setVisibility(View.GONE);
        floorSmallRecyclerView.setVisibility(View.GONE);
    }

    //当前变化有设备
    private void Ye_sequipment() {
        floorRecyclerView.setVisibility(View.VISIBLE);
        floorSmallRecyclerView.setVisibility(View.VISIBLE);
    }

    private void gotoAddRoomActivity(String floorSerialNo){
        Intent intent = new Intent(getContext(), AddRoomActivity.class);
        intent.putExtra("floorSerialNo", floorSerialNo);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshRoomDeviceEvent(RefreshRoomDeviceEvent event) {
        floors = LLFloorDBManager.getInstance(getContext()).getFloorByHouseSerialNo(AppApplication.getInstance().getCurrentHouseSerialNo());
        mFloorListBigAdapter.setData(floors);
        mFloorListSmallAdapter.setData(floors);
    }

    @Override
    public void onClick(View view) {}

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initData() {
        floors = LLFloorDBManager.getInstance(getContext()).getFloorByHouseSerialNo(AppApplication.getInstance().getCurrentHouseSerialNo());
        initRecyclerView();
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
